package com.app.service.impl;

/*
  @author 阿伟
  @create 2020-11-25:15:48
*/

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.app.service.OssService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadAliyun(MultipartFile file) {
        try {
            //站点地区
            String endpoint = "oss-cn-chengdu.aliyuncs.com";
            //acess_key_id
            String accessKeyId = "LTAI4Fz6Az9tBMGHLAD9DBHY";
            //acess_key_secret
            String accessKeySecret = "ozHOkgYZDz00qKhR3eqh1y3P7a0jqG";
            //bucket_name
            String bucketName = "20201126";

            //2 创建OssClient对象
            OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
            //3 获取文件信息，为了上传
            //文件输入流
            InputStream in = file.getInputStream();

            //文件名称
            String fileName = file.getOriginalFilename();
            // meta设置请求头
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentType("image/jpg");

            //上传图片
            ossClient.putObject(bucketName, "images/"+fileName, in, meta);
            //关闭ossClient
            ossClient.shutdown();

            //返回上传之后地址，拼接地址
            String uploadUrl = "https://"+bucketName+"."+endpoint+"/"+"images/"+fileName;
            return uploadUrl;
        }catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
